package com.one.square.common.zookeeper;

import com.one.square.common.zookeeper.lock.ZookeeperDistributedLock;
import com.one.square.common.zookeeper.template.ZookeeperTemplate;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import com.one.square.common.zookeeper.property.ZookeeperProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author cwm
 * @Description zokkeeper自动装配
 * @date 2021/10/29 下午12:55
 * @Version 1.0
 */
@EnableConfigurationProperties(ZookeeperProperty.class)
@Configuration
public class ZookeeperAutoConfiguration {

    /**
     * 初始化连接
     */
    @Bean(initMethod = "start", destroyMethod = "close")
    @ConditionalOnMissingBean
    public CuratorFramework curatorFramework(ZookeeperProperty property) {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(property.getBaseSleepTime(), property.getMaxRetries());
        return CuratorFrameworkFactory.builder()
                .connectString(property.getConnectString())
                .connectionTimeoutMs(property.getConnectionTimeout())
                .sessionTimeoutMs(property.getSessionTimeout())
                .retryPolicy(retryPolicy)
                .build();
    }
    @Bean
    @ConditionalOnMissingBean
    public ZookeeperTemplate zookeeperTemplate(CuratorFramework curatorFramework){
        return new ZookeeperTemplate(curatorFramework);
    }

    @Bean
    @ConditionalOnProperty(prefix = "one.square.lock", name = "lockerType", havingValue = "ZK")
    public ZookeeperDistributedLock zookeeperDistributedLock(CuratorFramework curatorFramework){
        return new ZookeeperDistributedLock(curatorFramework);
    }
}
